package com.kk.nb_order.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kk.nb_order.bean.Order;
import com.kk.nb_order.remote.SearchService;
import com.kk.nb_order.service.OrderService;
import com.woniuxy.boot.common.bean.EsOrder;
import com.woniuxy.boot.common.dto.EsOrderSearchDTO;
import com.woniuxy.boot.common.pojo.ResultObj;
import com.woniuxy.boot.common.util.EntityConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: K
 * @Date: 2024/12/14
 */
@RestController("adminOrderController")
@RequestMapping("admin/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private SearchService searchService;

    /**
     * 管理员查询所有订单
     *
     * @return
     */
    @GetMapping("list")
    public List<Order> list() {
        return orderService.list();
    }

    /**
     * 管理员根据条件查询
     *
     * @param esOrderSearchDTO
     * @return
     */
    @PostMapping("condition")
    public ResultObj condition(@RequestBody EsOrderSearchDTO esOrderSearchDTO) {
        System.out.println(esOrderSearchDTO);
        // 获取所有非空的查询条件
        Map<String, Object> queryConditions = getNonEmptyFields(esOrderSearchDTO);

        List<EsOrder> resultOrders;

        if (esOrderSearchDTO.getKeyword() == null || esOrderSearchDTO.getKeyword().isEmpty()) {
            // 如果没有提供keyword，则仅使用其他非空条件查询数据库
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryConditions.forEach((key, value) -> {
                switch (key) {
                    case "payStatus":
                        queryWrapper.eq("pay_status", value);
                        break;
                    case "minPrice":
                        queryWrapper.ge("price", value);
                        break;
                    case "maxPrice":
                        queryWrapper.le("price", value);
                        break;
                    case "payTime":
                        queryWrapper.ge("pay_time", value);
                        break;
                    case "nextPayTime":
                        queryWrapper.le("pay_time", value);
                        break;
                    default:
                        // 忽略其他可能的条件
                        break;
                }
            });
            List<Order> dbOrders = orderService.list(queryWrapper);
            resultOrders = dbOrders.stream()
                    .map(this::convertOrderToEsOrder) // 将Order转换为EsOrder
                    .collect(Collectors.toList());
        } else {
            // 如果提供了keyword，则先调用ES服务
            List<EsOrder> esOrders = searchService.getEsOrder(esOrderSearchDTO);

            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryConditions.remove("keyword"); // 不再需要这个条件
            queryConditions.forEach((key, value) -> {
                switch (key) {
                    case "payStatus":
                        queryWrapper.eq("pay_status", value);
                        break;
                    case "minPrice":
                        queryWrapper.ge("total_money", value);
                        break;
                    case "maxPrice":
                        queryWrapper.le("total_money", value);
                        break;
                    case "payTime":
                        queryWrapper.ge("pay_time", value);
                        break;
                    case "nextPayTime":
                        queryWrapper.le("pay_time", value);
                        break;
                    default:
                        // 忽略其他可能的条件
                        break;
                }
            });
            List<Order> dbOrders = orderService.list(queryWrapper);

            // 将Order转换为EsOrder
            List<EsOrder> convertedDbOrders = dbOrders.stream()
                    .map(this::convertOrderToEsOrder)
                    .collect(Collectors.toList());

            // 合并两个列表，去除重复项
            resultOrders = Stream.concat(esOrders.stream(), convertedDbOrders.stream())
                    .distinct()
                    .collect(Collectors.toList());
        }

        // 返回查询结果
        return ResultObj.ok().data(resultOrders);
    }

    // 转换Order到EsOrder的方法
    private EsOrder convertOrderToEsOrder(Order order) {
        if (order == null) {
            return null;
        }
        return EntityConverter.convert(order, EsOrder.class);
    }


    private Map<String, Object> getNonEmptyFields(EsOrderSearchDTO dto) {
        Map<String, Object> nonEmptyFields = new HashMap<>();

        // 检查payStatus
        if (dto.getPayStatus() != null && !dto.getPayStatus().isEmpty()) {
            nonEmptyFields.put("payStatus", dto.getPayStatus());
        }
        // 检查keyword
        if (dto.getKeyword() != null && !dto.getKeyword().isEmpty()) {
            nonEmptyFields.put("keyword", dto.getKeyword());
        }
        // 检查minPrice
        if (dto.getMinPrice() != null && dto.getMinPrice().compareTo(BigDecimal.ZERO) > 0) {
            nonEmptyFields.put("minPrice", dto.getMinPrice());
        }
        // 检查maxPrice
        if (dto.getMaxPrice() != null && dto.getMaxPrice().compareTo(BigDecimal.ZERO) > 0) {
            nonEmptyFields.put("maxPrice", dto.getMaxPrice());
        }
        // 检查payTime
        if (dto.getPayTime() != null) {
            nonEmptyFields.put("payTime", dto.getPayTime());
        }
        // 检查nextPayTime
        if (dto.getNextPayTime() != null) {
            nonEmptyFields.put("nextPayTime", dto.getNextPayTime());
        }

        return nonEmptyFields;
    }
}

